package networkInterface;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import main.ChatSystem;
import cs.remoteapp.Message;


/**
 * Implements sending of Message objects
 * 
 * <p>
 * <ul>
 * <li>Project: 	ChatSystemG3</li>
 * <li>Called by: 	ChatNI</li>
 * </ul>
 * </p>
 * 
 * @author COMBES Nicolas - LECHANTRE Arnaud
 * @see ChatNISender
 */
public class ChatNIMessageSender extends ChatNISender{
	
	/**
	 * Socket used to UDP sending
	 */
	private DatagramSocket socket;
	
	
	/**
	 * construct; socket initialization
	 */
	public ChatNIMessageSender() {
		try {
			this.socket = new DatagramSocket();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			System.out.println("Emission socket not created.");
		}
	}
	
	
	/**
	 * Sends a message to the designed ip address
	 * @param theMessage message to send
	 * @param remoteAddress address of remote user
	 */
	public void sendDatagram(Message theMessage, InetAddress remoteAddress){
		/* 
		 * Creating some byte code using a Message object
		 * using ByteArrayOoutputStream things. 
		 */
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			/*Creating an OOS linked with the BAOS*/
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			/*Converting theMessage into byte code*/
			oos.writeObject(theMessage);
			oos.flush();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		byte[] byteMsg = baos.toByteArray();
		/*
		 * Creating the packet once the message has been "converted" into byte code and sending it
		 */
		if (ChatSystem.debugMode) System.out.println("networkInterface.ChatNISender : " + byteMsg);
		DatagramPacket packet = new DatagramPacket(byteMsg, byteMsg.length/*Message length?*/, remoteAddress, ChatSystem.udpPortEmit);
	
			//this.socket = new DatagramSocket();
		try {
			socket.send(packet);
			if (ChatSystem.debugMode) {System.out.println("networkInterface.ChatNISender : Packet sent.");}
		} catch (IOException e) {
			if (ChatSystem.debugMode) System.out.println("networkInterface.ChatNISender : Couldn't send.");
		}
	}

	
	/**
	 * Closes socket
	 */
	@Override
	public void close() {
		this.socket.close();
	}
}
